import { Text, View, Image, StyleSheet, SafeAreaView, ScrollView, TouchableWithoutFeedback, ActivityIndicator } from 'react-native'
import React, { useState, useEffect } from 'react'
import { Cell, Popup } from '@pingtou/rn-vant'
import { setIsLogin } from "../../redux/features/appSlice"
import { connect } from 'react-redux'
import httpApi from "../../api"
import { pTx } from "../../utils/dimensions"
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import AsyncStorage from '@react-native-async-storage/async-storage';
import loadFromLocalStorages from "../../loadFromLocalStorages"


const SwitchAccount = (props) => {
    const realm = useRealm();
    const userInfoList = useQuery(schemaName.UserInfo)
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const { loadInitialData } = loadFromLocalStorages()
    const [loading, setLoading] = useState(false)

    const changeAccount = async (item) => {
        try {
            setLoading(true)
            await AsyncStorage.setItem("token", item.Token)
            realm.write(() => {
                for (const user of userInfoList) {
                    if (item.Id + "" == user.Id + "") {
                        user.Current = true
                    } else {
                        user.Current = false
                    }
                }
            })
            setTimeout(async () => {
                const res = await httpApi.verifyToken()
                if (res.code == 20) {
                    await loadInitialData()
                    props.setIsLogin(false)
                    props.navigation.navigate('chat')
                } else {
                    props.setIsLogin(true)
                    props.navigation.navigate('logIn')
                }
            })
        } catch (error) {
            console.log(error)
        }
        setLoading(false)
    }
    return (
        <SafeAreaView style={styles.container}>
            <ScrollView style={styles.scrollView}>
                <View style={styles.page}>
                    <Text style={styles.title}>轻触头像以切换账号</Text>
                    {
                        userInfoList.map((item, index) => {
                            return (
                                <TouchableWithoutFeedback disabled={loading} onPress={() => changeAccount(item)} key={index}>
                                    <View style={styles.cell}>
                                        <View style={styles.info}>
                                            <Image style={styles.profilePhoto} source={{ uri: httpApi.inline + (item.ProfilePhoto || httpApi.defaultAvatar) }}></Image>
                                            <Text style={styles.name}>{item.NickName}</Text>
                                        </View>
                                        <>

                                            {userInfo.Id == item.Id && <View style={styles.labelRight}>
                                                {loading ? <ActivityIndicator /> : <Text style={styles.icon}>
                                                </Text>}
                                                <Text style={styles.label}>
                                                    当前使用
                                                </Text>
                                            </View>
                                            }
                                        </>

                                    </View>
                                </TouchableWithoutFeedback>
                            )
                        })
                    }
                    <TouchableWithoutFeedback disabled={loading} onPress={() => props.navigation.navigate('createWalletMnemonic', { network: 56 })}>
                        <View style={styles.cell}>
                            <View style={[styles.info, { alignItems: "center" }]}>
                                <IconOutline style={styles.plus} name="plus-square" />
                                <Text style={styles.name}>添加账号</Text>
                            </View>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
            </ScrollView>
        </SafeAreaView>
    )
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
    setIsLogin
}

export default connect(mapStateToProps, mapDispatchToProps)(SwitchAccount)

const styles = StyleSheet.create({
    page: {

    },
    container: {
        flex: 1,
        paddingVertical: pTx(20),
    },
    scrollView: {
        paddingHorizontal: pTx(20),
    },
    title: {
        paddingVertical: pTx(40),
        fontSize: pTx(20),
        textAlign: "center"
    },
    cell: {
        marginBottom: pTx(15),
        padding: pTx(10),
        flexDirection: 'row',
        justifyContent: "space-between",
        backgroundColor: "#fff",
        borderRadius: pTx(6),
    },
    info: {
        flexDirection: 'row',
    },
    profilePhoto: {
        marginRight: pTx(15),
        width: pTx(50),
        height: pTx(50),
        borderRadius: pTx(6),
        backgroundColor: "#AFB5BD"
    },
    plus: {
        marginRight: pTx(15),
        fontSize: pTx(50),
        color: "#666666"
    },
    name: {
        fontSize: pTx(16),
        color: "#000"
    },
    labelRight: {
        flexDirection: 'row',
        alignItems: "center",
    },
    label: {
        fontSize: pTx(12),
        color: "#000"
    },
    icon: {
        marginRight: pTx(3),
        width: pTx(8),
        height: pTx(8),
        borderRadius: pTx(10),
        backgroundColor: "#33E190"
    }
})